package org.budo.support.java.security.util;

import java.nio.charset.Charset;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.budo.support.slf4j.Slf4j;
import org.slf4j.Logger;

/**
 * @version 1 (2018年3月22日下午2:52:48)
 * @since Java7
 */
public class AesUtil {
    private static final Logger log = Slf4j.getLogger();

    private static final String KEY_ALGORITHM = "AES";

    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";// 默认的加密算法

    public static String encrypt(String src, String key) {
        return encrypt(src, null, key);
    }

    public static String decrypt(String hex, String key) {
        return decrypt(hex, null, key);
    }

    /**
     * AES 加密操作
     * 
     * @param content  待加密内容
     * @param password 加密密码
     * @return 返回Base64转码后的加密数据
     */
    public static String encrypt(String src, Charset charset, String key) {
        if (null == src || null == key) {
            log.error("#37 input null, src=" + src + ", charset=" + charset + ", key=" + key);
            return null;
        }

        try {
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 创建密码器

            byte[] byteContent = null == charset ? src.getBytes() : src.getBytes(charset);

            cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(key));// 初始化为加密模式的密码器

            byte[] result = cipher.doFinal(byteContent);// 加密

            return bytesToHex(result);// 通过Base64转码返回
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * AES 解密操作
     * 
     * @param content
     * @param password
     */
    public static String decrypt(String hex, Charset charset, String key) {
        if (null == hex || null == key) {
            log.error("#63 input null, hex=" + hex + ", charset=" + charset + ", key=" + key);
            return null;
        }

        try {
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM); // 实例化
            cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key)); // 使用密钥初始化，设置为解密模式
            byte[] parseHexStr2Byte = hexToBytes(hex);
            byte[] result = cipher.doFinal(parseHexStr2Byte); // 执行操作
            return null == charset ? new String(result) : new String(result, charset);
        } catch (Throwable e) {
            throw new IllegalArgumentException("#80 charset=" + charset, e);
        }
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            stringBuffer.append(hex.toUpperCase());
        }
        return stringBuffer.toString();
    }

    /**
     * 将16进制转换为二进制
     */
    private static byte[] hexToBytes(String hex) {
        try {
            if (null == hex || hex.length() < 1) {
                return null;
            }

            byte[] bytes = new byte[hex.length() / 2];
            for (int i = 0; i < hex.length() / 2; i++) {
                String highStr = hex.substring(i * 2, i * 2 + 1);
                String lowStr = hex.substring(i * 2 + 1, i * 2 + 2);

                int high = Integer.parseInt(highStr, 16);
                int low = Integer.parseInt(lowStr, 16);
                bytes[i] = (byte) (high * 16 + low);
            }

            return bytes;
        } catch (Throwable e) {
            throw new RuntimeException("#117 hexToBytes error, hex=" + hex, e);
        }
    }

    /**
     * 返回生成指定算法密钥生成器的 KeyGenerator 对象
     */
    private static SecretKeySpec getSecretKey(final String password) {
        try {
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(password.getBytes());

            KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
            keyGenerator.init(128, secureRandom); // AES 要求密钥长度为 128
            SecretKey secretKey = keyGenerator.generateKey(); // 生成一个密钥
            return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);// 转换为AES专用密钥
        } catch (Throwable e) {
            throw new IllegalArgumentException(e);
        }
    }
}
